package com.rental.client.service.impl;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.rental.client.config.TencentCloudProperties;
import com.rental.client.service.CosService;
import com.rental.model.vo.CosUploadVo;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.UUID;



@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CosServiceImpl implements CosService {

    @Autowired
    private TencentCloudProperties tencentCloudProperties;

    private COSClient getPrivateCOSClient(){
        // 1 初始化用户身份信息（secretId, secretKey）。
        COSCredentials cred = new BasicCOSCredentials(tencentCloudProperties.getSecretId(), tencentCloudProperties.getSecretKey());
        // 2 设置 bucket 的区域, COS 地域的简称请参照 URL_ADDRESS
        Region region = new Region(tencentCloudProperties.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        // 这里建议设置使用 https 协议
        // 从 5.6.54 版本开始，默认使用了 https
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }


    @Override
    public CosUploadVo upload(MultipartFile file, String path) {
//        连接腾讯云
        COSClient cosClient = getPrivateCOSClient();
//        设置上传元数据信息
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(file.getSize());
        meta.setContentEncoding("UTF-8");
        meta.setContentType(file.getContentType());
//        向桶中保存信息
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String uploadPath = "house/"+ path + "/" + UUID.randomUUID().toString().replaceAll("-",".") + fileType;
//        获取腾讯云的存储位置
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(tencentCloudProperties.getBucketPrivate(), uploadPath, file.getInputStream(), meta);
            putObjectRequest.setStorageClass(StorageClass.Standard);
//            上传
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            cosClient.shutdown();

//            封装返回对象
            CosUploadVo cosUploadVo = new CosUploadVo();
            cosUploadVo.setUrl(uploadPath);
//            回显路径
            cosUploadVo.setShowUrl(getImgUrl(uploadPath));
            return cosUploadVo;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getImgUrl(String path) {
        if (!StringUtils.hasText(path)){
            return "";
        }
        COSClient cosClient = getPrivateCOSClient();
//        自动生成签名
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(tencentCloudProperties.getBucketPrivate(), path, HttpMethodName.GET);
//        生成的临时URL，有效时间为10天
        Date date = new DateTime().plusDays(10).toDate();
        request.setExpiration(date);
        URL url = cosClient.generatePresignedUrl(request);
        cosClient.shutdown();
        return url.toString();
    }
}
